package org.jash.shop2202.goods

import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alipay.sdk.app.PayTask
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.jash.shop2202.R
import org.jash.shop2202.databinding.ActivityPayBinding
import org.jash.shop2202.mvvm.BaseActivity
import org.jash.shop2202.mvvm.BaseViewModel
import org.jash.shop2202.utils.pay.PayResult
import org.jash.shop2202.utils.pay.util.OrderInfoUtil2_0


/**
 * 用于支付宝支付业务的入参 app_id。
 */

const val APPID = "9021000136678494"

/**
 * 用于支付宝账户登录授权业务的入参 pid。
 */

const val PID = "2088721035210245"

/**
 * 用于支付宝账户登录授权业务的入参 target_id。
 */

const val TARGET_ID = ""

/**
 * pkcs8 格式的商户私钥。
 *
 * 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
 * 使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
 * RSA2_PRIVATE。
 *
 * 建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
 * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
 */

const val RSA2_PRIVATE = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDDoabdnPkGjRplw18c2lcBgEwktoRILUSWdPCIymlmUyPiBDCJeITI2EswKguCNDSbHNAke1vgqqe5PPLNzEoRFfxVvQSBFDeTudJAvf/f3veRPDZKgNy/DzFtUuWadmBdcimRJoGTz/vhnxt7m/BxB35T6ih/47DjTfWp//xUiqPn6rvr1iacIW0CluT5+yw8r3rLG6H71sTdVRhu2iCh6HF655i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bA5FLuGrB5tgwEgZfRb4BfW7VdCJ0H17a4eX1a0ju6EQndfxuI+ZnnopSJBRz8CBIjAfSzUdMVR1lZZ0xksDwR6MDh9TcRAoGBAIRQxq5Ku82DbsIYG69kfwxrg2uOAv/4bJ3efAR9D/EcUK3NWs6P54tR0oT/Xia/a+2yKATBGFxHXJc3LZ/4gHnysDEEI04ptCmfdCo7ieR1XQ7O5dSH5ux16FiZi9f/FDgOb+oloIQATWujIBzLhD0Zc2vspQHv0dgYSraaLaI7"
const val RSA_PRIVATE = ""

@Route(path = "/shop/pay")

class PayActivity : BaseActivity<ActivityPayBinding, BaseViewModel>() {
    @Autowired
    @JvmField
    var content:String = ""
    @Autowired
    @JvmField
    var price:Float = 0f
    var disposable:Disposable? = null
    override fun initData() {
        ARouter.getInstance().inject(this)
    }

    override fun initView() {
//        setSupportActionBar(binding.toolbar)
//        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        binding.content.text = content
        binding.price.text = getString(R.string.price_format, price)
        binding.pay.setOnClickListener {
            disposable = Observable.fromCallable {
                val rsa2 = (RSA2_PRIVATE.length > 0)
                val params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2, price, content)
                val orderParam = OrderInfoUtil2_0.buildOrderParam(params)

                val privateKey = if (rsa2) RSA2_PRIVATE else RSA_PRIVATE
                val sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2)
                val orderInfo = "$orderParam&$sign"
                val alipay = PayTask(this)
                val result = alipay.payV2(orderInfo, true)
                PayResult(result)
            }.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    when(it.resultStatus) {
                        "9000" -> Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show()
                        else -> Toast.makeText(this, "支付失败, 原因: ${it.memo}", Toast.LENGTH_SHORT).show()
                    }
                }, {
                    it.printStackTrace()
                    Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
                })

        }
        val toggle =
            ActionBarDrawerToggle(this, binding.drawer, binding.toolbar, 0, 0)
        binding.drawer.addDrawerListener(toggle)
        toggle.syncState()
    }

    override fun onDestroy() {
        super.onDestroy()
        disposable?.takeIf { !it.isDisposed }?.dispose()
    }
}